package net.xdclass.forum.dao;

import net.xdclass.forum.domain.User;
import net.xdclass.forum.util.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class UserDao {
    QueryRunner queryRunner = new QueryRunner(DataSourceUtil.getDataSource());
    public int save(User user) throws Exception {
        String sql = "insert into user(phone, pwd, sex, img, create_time, role, username) values(?, ?, ?, ?, ?, ?, ?)";
        Object[] params = {
                user.getPhone(),
                user.getPwd(),
                user.getSex(),
                user.getImg(),
                user.getCreate_time(),
                user.getRole(),
                user.getUsername()
        };
        int i = 0;
        try {
            i = queryRunner.update(sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new Exception();
        }
        return i;
    }

    public User findByPhoneAndPwd(String phone, String pwdMD5) {
        String sql = "select * from user where phone = ? and pwd = ?";

        User user = null;
        try {
            user = queryRunner.query(sql, new BeanHandler<>(User.class),phone,pwdMD5);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }
}
